package com.yunfeng.web.test;

import com.alicom.mns.tools.DefaultAlicomMessagePuller;
import com.alicom.mns.tools.MessageListener;
import com.aliyun.mns.model.Message;
import com.aliyuncs.exceptions.ClientException;
import com.google.gson.Gson;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 只能用于接收云通信的消息，不能用于接收其他业务的消息
 */
public class ReceiveAlicomMsgDemo {

    private static Log logger = LogFactory.getLog(ReceiveAlicomMsgDemo.class);

    //以短信回执消息处理为例
    static class MyMessageListener implements MessageListener {

        private Gson gson = new Gson();

        @Override
        public boolean dealMessage(Message message) {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            //消息的几个关键值
            System.out.println("message receiver time from mns:" + format.format(new Date()));
            System.out.println("message handle: " + message.getReceiptHandle());
            System.out.println("message body: " + message.getMessageBodyAsString());
            System.out.println("message id: " + message.getMessageId());
            System.out.println("message dequeue count:" + message.getDequeueCount());
            System.out.println("Thread:" + Thread.currentThread().getName());
            try {
                Map<String, Object> contentMap = gson.fromJson(message.getMessageBodyAsString(), HashMap.class);

                //TODO 根据文档中具体的消息格式进行消息体的解析
                String arg = (String) contentMap.get("arg");
                String phoneNumber=(String)contentMap.get("phone_number");
                Boolean success=(Boolean)contentMap.get("success");
                String bizId=(String)contentMap.get("biz_id");
                String outId=(String)contentMap.get("out_id");
                String sendTime=(String)contentMap.get("send_time");
                String reportTime=(String)contentMap.get("report_time");
                String errCode=(String)contentMap.get("err_code");
                String errMsg=(String)contentMap.get("err_msg");

                System.out.println("onReceived");
                SmsDemo.SendMsg();
                //TODO 这里开始编写您的业务代码
                System.out.println(outId + phoneNumber);
            } catch (com.google.gson.JsonSyntaxException e) {
                System.out.println("Error");
                logger.error("error_json_format:" + message.getMessageBodyAsString(), e);
                //理论上不会出现格式错误的情况，所以遇见格式错误的消息，只能先delete,否则重新推送也会一直报错
                return true;
            } catch (Throwable e) {
                //您自己的代码部分导致的异常，应该return false,这样消息不会被delete掉，而会根据策略进行重推
                return false;
            }

            //消息处理成功，返回true, SDK将调用MNS的delete方法将消息从队列中删除掉
            return true;

        }
    }

    public static void main(String[] args){
        onReceiveListener();
    }

    public static void onReceiveListener(){
        DefaultAlicomMessagePuller puller = new DefaultAlicomMessagePuller();

        //设置异步线程池大小及任务队列的大小，还有无数据线程休眠时间
        puller.setConsumeMinThreadSize(6);
        puller.setConsumeMaxThreadSize(16);
        puller.setThreadQueueSize(200);
        puller.setPullMsgThreadSize(1);
        //和服务端联调问题时开启,平时无需开启，消耗性能
        puller.openDebugLog(false);

        String accessKeyId = "LTAIvMWSKnibyM3z";
        String accessKeySecret = "6N2XNZzoe1qU3F8J6hMVm82Q2CNFAI";
        //个人
//        String accessKeyId = "LTAIpJXOnbFZHsdo";
//        String accessKeySecret = "QE2Tn7j02gEDqX2yEqpjZRmzKEs84i";
        String messageType = "SmsUp";//短信回执：SmsReport，短信上行：SmsUp
//        String queueName = "Alicom-Queue-1651532135480535-SmsReport";//在云通信页面开通相应业务消息后，就能在页面上获得对应的queueName
        String queueName = "Alicom-Queue-1651532135480535-SmsUp";
        try {
            puller.startReceiveMsg(accessKeyId, accessKeySecret, messageType, queueName, new MyMessageListener());
        } catch (ClientException e) {
            System.out.println(e.toString());
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
            System.out.println(e.toString());
        }
    }
}